﻿using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLinePacking.Core;
using ZoneLinePacking.Enums;
using ZoneLinePacking.Models;
using ZoneLinePacking.Models.Entity;
using ZoneLinePacking.Models.Entity.BaseInfo;
using ZoneLinePacking.Services.DB;

namespace ZoneLinePacking.Common {

    /// <summary>
    /// 产品序列号帮助类
    /// </summary>
    public class ProductIndexHelper {

        public static int GetOldSystemIndex(ModelEnum model, WorkDirectionEnum LF, WorkDirectionEnum stationLF) {
            var _dal = PrismIocInfo.GetInstanceByIoc<IDbOperate<IFreeSqlMainContext>>();
            var index = 0;
            var dt = DateTime.Now;
            var days = (dt - DateTime.Parse("2020-01-01")).Days;

            var pieceModel = _dal.GetModel<PieceIndexModel>(p => p.DayIndex == days && p.Model == model && p.LF == LF && p.StationLF == stationLF);
            if (pieceModel != null) {
                index = pieceModel.Index;
            }
            return index;
        }

        public static int GetNewSystemIndex(ProductEntity productEntity, ePrintStartionCode ePrintStartionCode) {
            var _dal = PrismIocInfo.GetInstanceByIoc<IDbOperate<IFreeSqlMainContext>>();
            var index = 0;
            var indexObj = _dal.GetModel<IndexEntity>(o =>
            o.ProductID == productEntity.Id &&
            o.StationCode == ePrintStartionCode &&
            o.CurentDate == DateTime.Now.ToString("yyyyMMdd")
            );
            if (indexObj != null) {
                index = indexObj.CurentIndex;
            }
            return index;
        }

        /// <summary>
        /// 把旧软件序列号同步到新软件
        /// </summary>
        /// <param name="productEntity">产品</param>
        /// <returns></returns>
        public static (bool isOK,int curIndex) SynchronizeToNewSystemIndex(ProductEntity productEntity, ePrintStartionCode ePrintStartionCode) {
            var _dal = PrismIocInfo.GetInstanceByIoc<IDbOperate<IFreeSqlMainContext>>();
            (bool isOK, int curIndex) res = (false, 0);
            var customer = _dal.GetModel<CustomerEntity>(o => o.Id == productEntity.CustomerID);
            if (customer.Name == ModelEnum.LX.ToString()) { //只有理想的需要同步
                int oldSystemIndex = 0;
                switch (ePrintStartionCode) {
                    case ePrintStartionCode.Q_OP580_1:
                        oldSystemIndex = GetOldSystemIndex(ModelEnum.LX, productEntity.WorkDirection, WorkDirectionEnum.Left);
                        break;
                    case ePrintStartionCode.Q_OP580_2:
                        oldSystemIndex = GetOldSystemIndex(ModelEnum.LX, productEntity.WorkDirection, WorkDirectionEnum.Right);
                        break;
                    case ePrintStartionCode.H_OP640:
                        oldSystemIndex = GetOldSystemIndex(ModelEnum.LX, productEntity.WorkDirection, WorkDirectionEnum.Left);
                        break;
                    default:
                        break;
                }
                var indexEntity = _dal.GetModel<IndexEntity>(o =>
                o.ProductID == productEntity.Id
                && o.StationCode == ePrintStartionCode
                && o.CurentDate == DateTime.Now.ToString("yyyyMMdd")
                );
                LogManager.Info($"同步序列号，客户：{customer.Name}，左右型号：{productEntity.WorkDirection}，工站左右：{ePrintStartionCode}，旧系统序列号：{oldSystemIndex}，新系统序列号：{indexEntity?.CurentIndex}，开始");
                //同步到新表
                if (oldSystemIndex > 0 && indexEntity == null) {
                    indexEntity = new IndexEntity() {
                        CreateTime = DateTime.Now,
                        CurentDate = DateTime.Now.ToString("yyyyMMdd"),
                        CurentIndex = oldSystemIndex + 10,
                        ProductID = productEntity.Id,
                        StationCode = ePrintStartionCode
                    };
                } else if (oldSystemIndex > 0 && indexEntity != null && oldSystemIndex > indexEntity.CurentIndex) {
                    indexEntity.CurentIndex = oldSystemIndex + 10;
                } else if (oldSystemIndex > 0 && indexEntity != null && oldSystemIndex == indexEntity.CurentIndex) {
                    indexEntity.CurentIndex = oldSystemIndex + 10;
                } else {
                    LogManager.Info("同步序列号，当前新系统序号最新，无需同步.");
                }

                var affrows = _dal.GetFreeSql().InsertOrUpdate<IndexEntity>().SetSource(indexEntity).ExecuteAffrows();
                res.isOK = affrows > 0;
                res.curIndex = indexEntity != null ? indexEntity.CurentIndex : 0;
                LogManager.Info($"同步序列号，客户：{customer.Name}，左右型号：{productEntity.WorkDirection}，工站左右：{ePrintStartionCode}，旧系统序列号：{oldSystemIndex}，新系统序列号：{indexEntity?.CurentIndex}，结束。结果：{res}");
            }
            return res;
        }

        /// <summary>
        /// 把新软件序列号同步到旧软件
        /// </summary>
        /// <param name="productEntity">产品</param>
        /// <returns></returns>
        public static (bool isOK, int curIndex) SynchronizeToOldSystemIndex(ProductEntity productEntity, ePrintStartionCode ePrintStartionCode) {
            var _dal = PrismIocInfo.GetInstanceByIoc<IDbOperate<IFreeSqlMainContext>>();
            (bool isOK, int curIndex) res = (false, 0);
            var customer = _dal.GetModel<CustomerEntity>(o => o.Id == productEntity.CustomerID);
            if (customer.Name == ModelEnum.LX.ToString()) { //只有理想的需要同步
                //获取新系统的序列号
                int newSystemIndex = GetNewSystemIndex(productEntity, ePrintStartionCode);
                var dt = DateTime.Now;
                var days = (dt - DateTime.Parse("2020-01-01")).Days;
                //获取老系统的序号对象
                PieceIndexModel pieceModel = default;
                switch (ePrintStartionCode) {
                    case ePrintStartionCode.Q_OP580_1:
                        pieceModel = _dal.GetModel<PieceIndexModel>(p => p.DayIndex == days && p.Model == ModelEnum.LX && p.LF == productEntity.WorkDirection && p.StationLF == WorkDirectionEnum.Left);
                        break;
                    case ePrintStartionCode.Q_OP580_2:
                        pieceModel = _dal.GetModel<PieceIndexModel>(p => p.DayIndex == days && p.Model == ModelEnum.LX && p.LF == productEntity.WorkDirection && p.StationLF == WorkDirectionEnum.Right);
                        break;
                    case ePrintStartionCode.H_OP640:
                        pieceModel = _dal.GetModel<PieceIndexModel>(p => p.DayIndex == days && p.Model == ModelEnum.LX && p.LF == productEntity.WorkDirection && p.StationLF == WorkDirectionEnum.Left);
                        break;
                    default:
                        break;
                }
                LogManager.Info($"同步序列号，客户：{customer.Name}，左右型号：{productEntity.WorkDirection}，工站左右：{ePrintStartionCode}，新系统序列号：{newSystemIndex}，旧系统序列号：{pieceModel?.Index}，开始");
                //同步到旧系统
                if (newSystemIndex > 0 && pieceModel == null) {
                    pieceModel = new PieceIndexModel();
                    pieceModel.DayIndex = days;
                    pieceModel.Model = ModelEnum.LX;
                    pieceModel.LF = productEntity.WorkDirection;
                    pieceModel.Index = newSystemIndex;
                    switch (ePrintStartionCode) {
                        case ePrintStartionCode.Q_OP580_1:
                            pieceModel.StationLF = WorkDirectionEnum.Left;
                            break;
                        case ePrintStartionCode.Q_OP580_2:
                            pieceModel.StationLF = WorkDirectionEnum.Right;
                            break;
                        case ePrintStartionCode.H_OP640:
                            pieceModel.StationLF = WorkDirectionEnum.Left;
                            break;
                        default:
                            break;
                    }
                } else if (newSystemIndex > 0 && pieceModel != null && newSystemIndex > pieceModel.Index) {
                    pieceModel.Index = newSystemIndex;
                } else if (newSystemIndex > 0 && pieceModel != null && newSystemIndex == pieceModel.Index) {
                    pieceModel.Index = newSystemIndex;
                }
                var affrows = _dal.GetFreeSql().InsertOrUpdate<PieceIndexModel>().SetSource(pieceModel).ExecuteAffrows();
                res.isOK = affrows > 0;
                res.curIndex = pieceModel != null ? pieceModel.Index : 0;
                LogManager.Info($"同步序列号，客户：{customer.Name}，左右型号：{productEntity.WorkDirection}，工站左右：{ePrintStartionCode}，新系统序列号：{newSystemIndex}，旧系统序列号：{pieceModel?.Index}，结束。结果：{res}");
            }
            return res;
        }
    }
}
